﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Stitch.Database;

namespace Data.GameData.Entities
{
    public class EGame : EBaseObject
    {
        public static EGame LoadFromDB(Guid gameId)
        {
            string sqlStatement = "Select * from Game where id = '" + gameId.ToString() + "'";
            RunSQL(sqlStatement);

            DBRow dbRow = databaseResult.FetchArray();

            if (!databaseResult.MsSqlReader.HasRows)
                throw new Exception("No selected rows");
            if( databaseResult.MsSqlReader.FieldCount > 1 )
                throw new Exception("Too many rows");

            EGame newGame = new EGame();
            newGame.values = dbRow;

            return newGame;
        }

        internal static List<EGame> GetAll()
        {
            string sqlStatement = "Select * from Game";
            RunSQL(sqlStatement);

            List<EGame> eEntities = new List<EGame>();

            DBRow dbRow = databaseResult.FetchArray();

            while (dbRow != null)
            {
                EGame newGame = new EGame();
                newGame.values = dbRow;
                eEntities.Add(newGame);
                
                dbRow = databaseResult.FetchArray();
            }

            return eEntities;
        }

        internal void Delete()
        {
            string sqlStatement = "DELETE FROM Game WHERE id = '" + values["id"].ToString() + "'";
            RunNonSelectSQL(sqlStatement);
        }

        internal void SaveToDB(bool isNew)
        {
            string sqlStatement;

            if( isNew)
            {
                sqlStatement = "INSERT INTO Game (id, name, turnNumber, day, pulse) VALUES ("
                    + "'" + values["id"] + "', "
                    + "'" + values["name"] + "', "
                    + values["turnNumber"] + ", "
                    + values["day"] + ", "
                    + values["pulse"]+ ")";
            }
            else
            {
                sqlStatement = "UPDATE Game  SET "
                    + "name = '" + values["name"] + "', "
                    + "turnNumber = " + values["turnNumber"] + ", "
                    + "day = " + values["day"] + ", "
                    + "pulse = " + values["pulse"]
                    + " WHERE id = '" + values["id"] + "'";
            }

            RunNonSelectSQL(sqlStatement);
        }
    }
}
